<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-08-12 19:12
 *
 * Version: 2.0
 */

namespace App\Modules\Order\Criterias;


use Flower\Core\Repository\Contracts\RepositoryInterface;
use Flower\Core\Repository\Criterias\BaseCriterias;

class getRoyaltyDataCriteria extends BaseCriterias
{
	private $params;

	public function __construct($storeId, $type=null,$barberId = null, $itemIds = null, $date = null)
	{
		$this->params = [
			'type' => $type,
			'store_id'   => $storeId,
			'barber_id'  => $barberId,
			'date'       => $date,
			'item_id' => $itemIds
		];
	}

	public function apply($model, RepositoryInterface $repository)
	{
		$isSetDate = !empty($this->params['date']);
		$year = 0;$month=0;
		if ($isSetDate) {
			$date = explode('-', $this->params['date']);
			$year = $date[0];
			$month = $date[1];
		}
		$map['store_id'] = $this->params['store_id'];
		empty($this->params['type']) ? : $map['type'] = $this->params['type'];
		empty($this->params['barber_id']) ? : $map['user_id'] = $this->params['barber_id'];

		return $model->selectRaw('sum(amount) as royalty_amount')
			->when($isSetDate, function ($query) use ($year, $month) {
				$query->whereYear('created_at', $year)->whereMonth('created_at', $month);
			})
			->whereIn('item_id',$this->params['item_id'])
			->where($map);
	}

}